<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="公司名称" prop="companyId">
            <el-select
              class="slese"
              v-model="queryParams.companyId"
              placeholder="请选择公司"
              ref="selectRef"
              @change="companyChanged($event)"
              style="width: 240px;"
              :clearable="useCompany.companyId?false:true"
            >
              <el-option
                class="communityDropdown"
                v-for="item in companyList"
                :key="item.companyId"
                :label="item.companyName"
                :value="item.companyId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="项目名称" prop="projectId">
            <el-select class="slese" v-model="queryParams.projectId" placeholder="请选择项目" ref="selectRef" style="width: 240px;">
              <el-option
                class="communityDropdown"
                v-for="item in projectList"
                :key="item.projectId"
                :label="item.projectName"
                :value="item.projectId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="在职状态" prop="status">
            <el-select class="slese" v-model="queryParams.status" placeholder="请选择在职状态" clearable ref="selectRef" style="width: 240px;">
              <el-option class="communityDropdown" key="0" label="在职" value="0" />
              <el-option class="communityDropdown" key="1" label="离职" value="1" />
            </el-select>
          </el-form-item>

          <el-form-item label="薪资年月" prop="salaryPaymentDate">
            <el-date-picker v-model="queryParams.salaryPaymentDate" value-format="YYYY-MM" type="month" placeholder="请选择月份" />
          </el-form-item>

          <el-form-item label="姓名" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:laborCostTotal:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:laborCostTotal:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:laborCostTotal:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:laborCostTotal:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Upload" @click="handleUpload">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExportTemplate">导出模板</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="laborCostTotalList" @selection-change="handleSelectionChange" :height="windowHeight">
        <el-table-column fixed type="selection" width="55" align="center" />
        <el-table-column fixed label="公司名称" align="center" prop="companyName" />
        <el-table-column fixed label="隶属项目" align="center" prop="projectName" width="200" />
        <el-table-column fixed label="人员信息" align="center" prop="name" />

        <el-table-column label="岗位" align="center" prop="post" />
        <el-table-column label="薪资年月" width="110" align="center" prop="salaryPaymentDate" />
        <el-table-column label="基础工资" align="center" prop="basePay" />
        <el-table-column label="岗位津贴" align="center" prop="postAllowance" />
        <el-table-column label="其他津贴" align="center" prop="otherAllowance" />
        <el-table-column label="服装补贴" align="center" prop="clothingAllowance" />
        <el-table-column label="应发工资" align="center" prop="salaryPayable" />
        <el-table-column label="加班费" align="center" prop="overtimePay" />
        <el-table-column label="未满月工资扣除" align="center" prop="deductWorkFullHoursPay" />
        <el-table-column label="扣当月个人公积金" align="center" prop="deductingDyPersonalProvidentFund" />
        <el-table-column label="补服装补贴" align="center" prop="patchClothingSubsidy" />
        <el-table-column label="其他扣除" align="center" prop="otherDeduct" />
        <el-table-column label="月度优秀员工" align="center" prop="monthlyOutstandingEmployee" />
        <el-table-column label="工资实发数" align="center" prop="actualSalaryPaid" />
        <el-table-column label="当月社保" align="center" prop="dySocialSecurity" />
        <el-table-column label="当月单位公积金" align="center" prop="dyUnitProvidentFund" />
        <el-table-column label="下月雇主责任险" align="center" prop="employerLiabilityInsurance" />
        <el-table-column label="劳务管理费" align="center" prop="laborManagementFee" />
        <el-table-column label="劳务费用合计" align="center" prop="totalLaborCosts" />
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:laborCostTotal:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['business:laborCostTotal:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 导入数据 -->
    <el-dialog class="importData" v-model="importDataDialog" title="导入工资数据" width="500">
      <!-- <el-col :span="18"> -->
      <el-form :model="importDataForm" ref="importDataFormRef" :rules="importDataRules">
        <el-form-item label="导入公司" prop="companyId">
          <el-select class="slese" v-model="importDataForm.companyId" placeholder="请选择公司" ref="selectRef" style="width: 240px;">
            <el-option
              class="communityDropdown"
              v-for="item in companyList"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- </el-col> -->
      <!-- <el-col :span="6" class="text-center"> -->
      <div class="import-btn">
        <el-upload
          class="upload-demo"
          action=" "
          :limit="1"
          :before-upload="beforeAvatarUpload"
          :http-request="handleUploadFiles"
          ref="fileUploadRef"
        >
          <el-button type="primary" plain>选择文件</el-button>
        </el-upload>
      </div>
      <!-- </el-col> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cannelImportData">取消</el-button>
          <!-- <el-button :loading="buttonImportDataLoading" type="primary" @click="cannelImportData"> 确定 </el-button> -->
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LaborCostTotal" lang="ts">
import { listLaborCostTotal, getLaborCostTotal, delLaborCostTotal, addLaborCostTotal, updateLaborCostTotal } from '@/api/business/wages';
import { LaborCostTotalVO, LaborCostTotalQuery, LaborCostTotalForm } from '@/api/business/wages/types';
import request from '@/utils/request';
import useCompanyStore from '@/store/modules/company';
import { listCompany } from '@/api/business/company';
import { listProject } from '@/api/business/project';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();

const useCompany = useCompanyStore();
const laborCostTotalList = ref<LaborCostTotalVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const laborCostTotalFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: LaborCostTotalForm = {
  projectId: undefined,
  status: undefined,
  name: undefined,
  companyId: undefined,
  laborCostTotalId: undefined,
  peopleInfoId: undefined,
  post: undefined,
  overtimePay: undefined,
  basePay: undefined,
  postAllowance: undefined,
  otherAllowance: undefined,
  clothingAllowance: undefined,
  salaryPayable: undefined,
  deductWorkFullHoursPay: undefined,
  deductingDyPersonalProvidentFund: undefined,
  patchClothingSubsidy: undefined,
  otherDeduct: undefined,
  monthlyOutstandingEmployee: undefined,
  actualSalaryPaid: undefined,
  dySocialSecurity: undefined,
  dyUnitProvidentFund: undefined,
  employerLiabilityInsurance: undefined,
  laborManagementFee: undefined,
  totalLaborCosts: undefined,
  salaryPaymentDate: undefined,
  remark: undefined,
}
const data = reactive<PageData<LaborCostTotalForm, LaborCostTotalQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    projectId: undefined,
    status: undefined,
    name: undefined,
    companyId: undefined,
    laborCostTotalId: undefined,
    peopleInfoId: undefined,
    post: undefined,
    overtimePay: undefined,
    basePay: undefined,
    postAllowance: undefined,
    otherAllowance: undefined,
    clothingAllowance: undefined,
    salaryPayable: undefined,
    deductWorkFullHoursPay: undefined,
    deductingDyPersonalProvidentFund: undefined,
    patchClothingSubsidy: undefined,
    otherDeduct: undefined,
    monthlyOutstandingEmployee: undefined,
    actualSalaryPaid: undefined,
    dySocialSecurity: undefined,
    dyUnitProvidentFund: undefined,
    employerLiabilityInsurance: undefined,
    laborManagementFee: undefined,
    totalLaborCosts: undefined,
    salaryPaymentDate: undefined,
    remark: undefined,
    params: {
    }
  },
  rules: {
    laborCostTotalId: [
      { required: true, message: "劳务表id不能为空", trigger: "blur" }
    ],
    peopleInfoId: [
      { required: true, message: "人员信息id不能为空", trigger: "blur" }
    ],
    post: [
      { required: true, message: "岗位不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/* 上传文件 */
const fileUploadRef = ref<ElUploadInstance>();

const companyList = ref()
const companyQueryParams = ref({
  pageNum: 1,
  pageSize: 100,
  companyId: undefined,
})

const projectList = ref()
const projectQueryParams = ref({
  pageNum: 1,
  pageSize: undefined,
  companyId: useCompany.companyId,
})

const importDataRules = ref({
  companyId: [
    { required: true, message: "公司不能为空", trigger: "blur" }
  ]
})

/** 查询劳务列表 */
const getList = async () => {
  loading.value = true;
  const res = await listLaborCostTotal(queryParams.value);
  laborCostTotalList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  sessionStorage.setItem('wages','')
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  sessionStorage.setItem('wages','')
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  const date = new Date();
  var currentYear = date.getFullYear();
  const currentMonth = date.getMonth() + 1;
  queryParams.value.salaryPaymentDate = currentYear+'-'+currentMonth
  queryParams.value.companyId = useCompany.companyId
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: LaborCostTotalVO[]) => {
  ids.value = selection.map(item => item.laborCostTotalId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  sessionStorage.setItem('wages',JSON.stringify(queryParams.value))
  router.push({ path: '/administration/wagesAdd', query: { type:'add' } })

}

/** 修改按钮操作 */
const handleUpdate = async (row?: LaborCostTotalVO) => {
  sessionStorage.setItem('wages',JSON.stringify(queryParams.value))
  const _id = row?.laborCostTotalId || ids.value[0]
  router.push({ path: '/administration/wagesAdd', query: { type:'edit',id: _id } })

}

/** 删除按钮操作 */
const handleDelete = async (row?: LaborCostTotalVO) => {
  const _laborCostTotalIds = row?.laborCostTotalId || ids.value;
  await proxy?.$modal.confirm('是否确认删除数据？').finally(() => loading.value = false);
  await delLaborCostTotal(_laborCostTotalIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  let companyName = ''
  if(queryParams.value.companyId) {
    useCompany.companyList.forEach(item => {
      if(item.companyId == useCompany.companyId) {
        companyName=`（${item.companyName}）`
        if(queryParams.value.projectId) {
          projectList.value.forEach(ele => {
            if(ele.projectId == queryParams.value.projectId) {
              companyName=`（${item.companyName}-${ele.projectName}）`
            }
          })
        }
      }
    })
  }
  let data = '薪资'
  if(queryParams.value.salaryPaymentDate) {
    let arr = queryParams.value.salaryPaymentDate.split('-')
    data = arr[0] + '年' + arr[1] + '月薪资'
  }
  proxy?.download('business/laborCostTotal/export', {
    ...queryParams.value,
  }, `${data}结算表${companyName}.xlsx`)
}

/** 导出模板按钮操作 */
const handleExportTemplate = () => {
  proxy?.$download.downloadTemplate('2')
}

const importDataForm = ref({
  companyId:undefined,
})
const importDataDialog = ref(false)
const importDataFormRef = ref<ElFormInstance>();

// 导入按钮操作
const handleUpload = () => {
  importDataDialog.value = true
  importDataForm.value.companyId = useCompany.companyId
}

/** 取消导入数据 */
const cannelImportData = async () => {
  importDataDialog.value = false
  restImportData()
}

/* 重置导入数据 */
const restImportData = () => {
  importDataForm.value.companyId = undefined
  importDataFormRef.value?.resetFields();
  fileUploadRef.value?.clearFiles();
}

/** 上传文件前 */
const beforeAvatarUpload = (file:any) =>{
  let index = file.name.lastIndexOf('.')
  let str = file.name.substr(index + 1)
  if (!importDataForm.value.companyId) {
    ElMessage.error('请选择导入公司!')
    return false
  } else if ( ['xlsx'].indexOf(str.toLowerCase()) == -1) {
    ElMessage.error('请选择正确的文件！')
    return false
  }
  return true
}

/** 上传文件 */
const handleUploadFiles = (file: any) => {
  let data = new FormData();
  data.append('companyId', importDataForm.value.companyId);
  data.append('file', file.file);
  let errArr: string[] = []
  let errArrObj
  request({
      url: '/business/laborCostTotal/excelLaborCostTotalAll',
      headers: {
        "Content-Type": "multipart/form-data",
        isToken: true
      },
      method: 'post',
      data:data,
      onUploadProgress: function (e) {
        proxy?.$modal.loading("正在上传文件，请稍候...");
    }
  }).then(async res=> {
      if(JSON.stringify(res.data)!=='{}'){
        proxy?.$modal.closeLoading();
        fileUploadRef.value?.clearFiles();
        Object.keys(res.data).forEach(function(key) {
          var value = objectToString(res.data[key])
          errArrObj = `<strong>` + key + ': ' + `</strong>` + value + `；<br>`
          errArr.push(errArrObj)
        });
        let errRes = errArr.join('')
        cannelImportData()
        ElMessage({
          dangerouslyUseHTMLString: true,
          message: `<div class="wrap-semicolon">${errRes}</div>`,
          type: 'error',
        })
      }else{
        proxy?.$modal.closeLoading();
        await cannelImportData()
        await getList()
      }
  }).catch(err=>{
    proxy?.$modal.closeLoading();
    cannelImportData()
  })
  return true;
}

const objectToString = (obj) => {
  return Object.keys(obj)
    .map(key => `${key}: ${obj[key]}`)
    .join(', ');
}

/** 查询公司列表 */
const getCompanyList =async () => {
  companyQueryParams.value.companyId = useCompany.companyId
  const res = await listCompany(companyQueryParams.value);
  companyList.value = res.rows;
}

/** 查询项目列表 */
const getProjectList =async (id?:any) => {
  projectQueryParams.value.companyId = id ? id : useCompany.companyId
  const projectRes = await listProject(projectQueryParams.value);
  projectList.value = projectRes.rows
}

const companyChanged = (id: any) =>{
  console.log(id)
  console.log(queryParams.value.companyId)
  getProjectList(id)
}

//用深度监听单位变化
watch(() => useCompany.companyId, (newVal, oldVal) => {
  queryParams.value.companyId = useCompany.companyId
  getList()
  getProjectList()
  getCompanyList()
}, { deep: true });

const windowHeight = ref(500)
onMounted(async() => {
  try {
    if(sessionStorage.getItem('wages')!='') {
      queryParams.value = JSON.parse(sessionStorage.getItem('wages'))
    }else {
      queryParams.value.companyId = useCompany.companyId
      const date = new Date();
      var currentYear = date.getFullYear();
      const currentMonth = date.getMonth() + 1;
      queryParams.value.salaryPaymentDate = currentYear+'-'+currentMonth
    }
  } catch (error) {}
  await getCompanyList();
  await getProjectList();
  await getList();

  let pageHeight = Math.max(
    document.documentElement.clientHeight,
    window.innerHeight || 0
  );
  windowHeight.value = pageHeight - 360
});
</script>
<style>
.wrap-semicolon{
  line-height: 1.5;
}
</style>
